
<template>
  <div class="app-container" v-loading="loading">
	  <div class="search-container  app_ny">
	  	<div class="div2" style="position: relative">
	  		<el-row :gutter="12" style="width: 100%">
	  			<el-col :span="3">
	  				 <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
	  			</el-col>
	  			<el-col :span="6">
	  				<el-button :loading="loading" type="primary" @click="handleQuery"><template
	  						#icon><i-ep-search /></template>查询</el-button>
	  			</el-col>
	  		</el-row>
	  		<FilterColumn class="filtBox" @handleRefresh="resetQuery()" ></FilterColumn>
	  	</div>
	  </div>
	  
    <el-card shadow="never" >
     
	  <div class="action-row">
		<el-button v-hasPerm="['Dzb/save']"  @click="openDialog()" type="primary" plain><template #icon><i-ep-plus /></template>新增</el-button>
	  </div>

      <el-table v-loading="loading" :data="dataList"  :tree-props="{
        children: 'children',
        hasChildren: 'hasChildren',
      }" row-key="id" default-expand-all border size="small" @row-click="onRowClick">
	  <el-table-column type="index" label="序号" align="center" width="80" />
        <el-table-column label="名称" min-width="200">
          <template #default="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>

        <el-table-column label="党支部成员总数" align="center" prop="count">
          <template #default="scope">
            <el-text class="mx-1" type="success">{{ scope.row.count }}</el-text> 
			<el-link @click="toUser(scope.row.id)"  type="primary">查看</el-link>
          </template>
        </el-table-column>

        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['Dzb/save']" type="success" link size="small" @click.stop="openDialog(scope.row.id)">
				<template #icon><i-ep-plus/></template>新增
            </el-button>
            <el-button v-hasPerm="['Dzb/update']" type="primary" link size="small"
              @click.stop="openDialog(undefined, scope.row.id)">
			  <template #icon><i-ep-edit/></template>编辑
            </el-button>
            <el-button v-hasPerm="['Dzb/delete']" type="danger" link size="small"
              @click.stop="handleDelete(scope.row.id)">
			  <template #icon><i-ep-delete/></template>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" destroy-on-close append-to-body width="750px"
      @close="closeDialog">
      <el-form ref="dataFormRef" :default-expand-all="true" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="所属上级" prop="pid">
          <el-tree-select v-model="formData.pid" placeholder="选择上级架构" :default-expand-all="true" :data="dataOptions" :props="dataProps" filterable
            check-strictly :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="所属公司" prop="cid">
          <el-tree-select v-model="formData.cid" placeholder="选择所属公司" :default-expand-all="true" :data="companyOptions" :props="companyProps" filterable
            check-strictly :render-after-expand="false" />
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" style="width: 100px" controls-position="right" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup lang="ts">
defineOptions({
  // eslint-disable-next-line vue/no-reserved-component-names
  name: "Dzb",
  inheritAttrs: false,
});
import { useRouter,useRoute } from 'vue-router';
import { DataQuery, DataForm, DataVO } from "@/api/dzb/types";
import {
  listDzb,
  getDzbForm,
  listDzbOptions,
  addDzb,
  deleteDzb,
  updateDzb,
  listCompanyOptions,
} from "@/api/dzb";
import { root } from "postcss";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
});

const queryParams = reactive<DataQuery>({});
const dataList = ref<DataVO[]>([]);

const dataOptions = ref<OptionType[]>([]);

const companyOptions = ref<OptionType[]>([]);

const dataProps = {
  label: 'name',
  children: 'children',
  value: 'id',
}

const companyProps = {
  label: 'name',
  children: 'children',
  value: 'id',
}

const formData = reactive<DataForm>({
  pid: undefined,
  name: "",
  sort: 50,
});

const rules = reactive({
  pid: [{ required: true, message: "请选择所属上级", trigger: "blur" }],
  cid: [{ required: true, message: "请选择所属公司", trigger: "blur" }],
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  sort: [{ required: true, message: "请输入排序值", trigger: "blur" }],
});

// 选择表格的行架构ID
const selectedRowDataId = ref<number | undefined>();

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  listDzb(queryParams)
    .then(({ data }) => {
      dataList.value = data;
    })
    .then(() => {
      loading.value = false;
    });
}

/**
 * 查询重置
 */
function resetQuery() {
  handleQuery();
}
/**
 * 行点击事件
 */
function onRowClick(row: DataVO) {
  selectedRowDataId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父ID
 * @param menuId ID
 */
function openDialog(parentId?: number, Id?: number) {
  listDzbOptions()
    .then(({ data }) => {
      dataOptions.value =  [{ id: 0, name: "顶级架构", children: data }];
    })
    .then(() => {
      dialog.visible = true;
      if (Id) {
        dialog.title = "编辑架构";
        getDzbForm(Id).then(({ data }) => {
          Object.assign(formData, data);
        });
      } else {
        dialog.title = "新增架构";
        formData.pid = parentId;
      }
    });
}

/**
 * 架构保存提交
 */
function submitForm() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      const Id = formData.id;
      if (Id) {
        updateDzb(Id, formData).then(() => {
          ElMessage.success("修改成功");
          closeDialog();
          handleQuery();
        });
      } else {
        addDzb(formData).then(() => {
          ElMessage.success("新增成功");
          closeDialog();
          handleQuery();
        });
      }
    }
  });
}

/**
 * 删除架构
 * @param departmentId 架构ID
 */
function handleDelete(Id: number) {
  if (!Id) {
    ElMessage.warning("请勾选删除项");
    return false;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteDzb(Id).then(() => {
        ElMessage.success("删除成功");
        handleQuery();
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.pid = undefined;
  formData.cid = undefined;
  formData.name = undefined;
  formData.sort = 50;

}

const router = useRouter();
function toUser(did){
    router.push({ 
        path:`/org/dangwei`,
        query:{did:did}
    })
    .catch(err => {
        console.error(err);
    });
}

onMounted(() => {
  handleQuery();
  listCompanyOptions()
    .then(({ data }) => {
      companyOptions.value = data;
    })
});
</script>

